/* Example program for moving a Servo.

  TODO: next step - use ADC from resistor to control the servo
*/
#include <avr/io.h>
#include <avr/interrupt.h>

#ifndef F_CPU
#warning "F_CPU was not defined yet, now using 3686400 Hz"
#define F_CPU 3686400UL     /* 3.6864 Mhz */
#endif
#include <util/delay.h>

uint16_t g_iLastDelay=0;

#define OSHIFT_DDR DDRB
#define OSHIFT_PORT PORTB

#define SIN 2
#define SCK 3
#define SCL 4
#define RCK 5

void shift_out(uint8_t byte)
{
  uint8_t i=8;

  // first, reset
  OSHIFT_PORT &= ~(1 << SCL);
  OSHIFT_PORT = 1 << SCL;
  
  while(i>0)
  {
    --i;
    // reverse?!
    if ( byte & (1<<i))
      // turn bit ON
      OSHIFT_PORT &= ~(1 << SIN);
    else
      OSHIFT_PORT |= 1 << SIN;

    // clock signal 0-1
    OSHIFT_PORT |= 1<<SCK;
    OSHIFT_PORT &= ~(1<<SCK);
  }
  // finally, take over the register to output
  OSHIFT_PORT |= 1<<RCK;
  OSHIFT_PORT &= ~(1<<RCK);
}

void init(void)
{
  // output only on PortB, first 6 bits
  OSHIFT_DDR = 0x3F;
  // turn all LEDs off
}

int main (void)
{
  init();  
  sei(); // interrupts ON
 
  // now loop forever
  while(1)
  {
    shift_out(0xAA);
    _delay_ms(500);
    shift_out(0x55);
    _delay_ms(500);
  }

  // pointless, will never be reached
  return 0;
}
